package servlets;

import java.io.IOException;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import usecases.GestionConcoursPizza;
import domaine.ApprentiPizzaiolo;
import domaine.ConcoursPizza;

/**
 * Servlet implementation class RejoindrePartie
 */
@WebServlet(name = "rejoindrepartie.html")
public class RejoindrePartie extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionConcoursPizza gestionConcours;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("salledattente.html");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if(request.getSession().getAttribute("apprenti")==null){
			response.sendRedirect("index.html");
			return;
		}	
		Map<String, ConcoursPizza> lesConcours = (Map<String, ConcoursPizza>) this
				.getServletContext().getAttribute("lesConcours");
		HttpSession sessionApprenti = request.getSession();

		synchronized (sessionApprenti) {
			ApprentiPizzaiolo apprenti = (ApprentiPizzaiolo) sessionApprenti
					.getAttribute("apprenti");

			ConcoursPizza concours = lesConcours.get(request
					.getParameter("partieRejoindre"));

			if(concours==null){
				response.sendRedirect("salledattente.html");
				return;
			}
			if (!concours.ajouterApprenti(apprenti)) {
				RequestDispatcher rd = getServletContext().getNamedDispatcher(
						"salledattente.html");
				rd.forward(request, response);
			}

			else {
				sessionApprenti.setAttribute("coucoursRejoint",
						concours.getNomConcours());

				RequestDispatcher rd = getServletContext().getNamedDispatcher(
						"plateau.html");
				request.setAttribute("devoir", "attendreDebutJeu");
				rd.forward(request, response);
			}

		}

	}

}
